package com.roc.web.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.OperRole;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.TblArea;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblOrgMain;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;


/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Company: </p>
* @author 
* @date 2016年11月21日上午11:45:33
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/pages")
public class AdminMerchantAction extends PaginationBaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5236170890634487270L;
	
	private Logger logger=LogManager.getLogger(AdminMerchantAction.class);
	

	private Operators operators;
	
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	private List<TblArea> areaList=new ArrayList<TblArea>();
	
	private Map<String, String> roleTypes=new TreeMap<String, String>();
	
	private String orgCode;
	private String areaId;
	private String agentTo;
	
	public String getAgentTo() {
		return agentTo;
	}
	public void setAgentTo(String agentTo) {
		this.agentTo = agentTo;
	}
	public String getAreaId() {
		return areaId;
	}
	public void setAreaId(String areaId) {
		this.areaId = areaId;
	}
	public String getOrgCode() {
		return orgCode;
	}
	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}
	public List<TblInsInf> getOrgList() {
		return orgList;
	}
	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}
	public Map<String, String> getRoleTypes() {
		return roleTypes;
	}
	public void setRoleTypes(Map<String, String> roleTypes) {
		this.roleTypes = roleTypes;
	}
	//private Map<String, String> merLevel=new HashMap<String, String>(); 
	private List<Object> profitRsList=new ArrayList<Object>();
	private MerchantSearchCondition searchCondition;
	private String msg;
	
	
	@Autowired 
	IMerchantServices merchantServices;
	@Autowired
	IPagenitionService pagenitionService;

	@Autowired
	IorgService orgService;
	@Autowired
	IAgentService agentService;
	

	@Action(value = "merAdd", results = {
			@Result(name = "success", location = "/pages/regist.jsp"),
			@Result(name = "input", location = "/pages/regist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	@Validations(requiredStrings = {
			@RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "operators.accountNo", message = "请输入账号"),
			@RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "operators.mobile", message = "请输入手机号"),
			@RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "operators.cardType", message = "请输选择证件"),
			@RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "operators.cardNo", message = "请输入证件号"),
			@RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "operators.address", message = "请输输入详细地址")
			//@RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "merchant.parentMerchantNo", message = "请输入代理商所属代理商"),
			//@RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "address.detail", message = "请选择代理商详细地址") // ,
	// @RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName =
	// "checkCode", message = "请输入手机验证码")

	})
	
	

	
	public String merchantAdd() throws Exception {
		Operators loginOerpators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		String pwd = "";
		try{
			if(!loginOerpators.getRoleType().equals(Role.SYSTEM.getCode())&&!loginOerpators.getRoleType().equals(Role.O_MANAGER.getCode())&&!loginOerpators.getRoleType().equals(Role.AGENT.getCode())&&!loginOerpators.getRoleType().equals(Role.O_MANAGER.getCode())&&!loginOerpators.getRoleType().equals(Role.AGENT.getCode())&&!loginOerpators.getRoleType().equals(Role.OPERATORS_COMM.getCode())&&!loginOerpators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			
			   init();
				if(operators==null){
					addActionMessage("操作员信息不完善，请重试");
					return INPUT;
				}
				Operators tempMer=merchantServices.findMerchantByNo(operators.getAccountNo());
				if(tempMer!=null){
					addActionMessage("账号【"+operators.getAccountNo()+"】已存在");
					return INPUT;
				}
				operators.setSuperiorId(loginOerpators.getId());
				operators.setMerberFlag(loginOerpators.getMerberFlag());
				operators.setAreaCode(loginOerpators.getAreaCode());
				if(operators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())){
					operators.setGroupCd("2");
				}else{
					operators.setGroupCd(loginOerpators.getGroupCd() );
				}
				operators.setCompanyid(loginOerpators.getCompanyid());
				
				if(Role.O_MANAGER.getCode().equals(loginOerpators.getRoleType())){
					operators.setOneagentid(loginOerpators.getOneagentid());
					operators.setFlag(Constance.OPERATORS_FLAG_OEM);
				}else if(Role.SYSTEM.getCode().equals(loginOerpators.getRoleType())){
					operators.setFlag(Constance.OPERATORS_FLAG_SELF);
					operators.setOneagentid("48502000");
				}else if(Role.AGENT.getCode().equals(loginOerpators.getRoleType())){
					operators.setFlag(Constance.OPERATORS_FLAG_SELF);
					operators.setOneagentid(loginOerpators.getOneagentid());
				}else if(Role.OPERATORS_COMM.getCode().equals(loginOerpators.getRoleType())||Role.OPERATORS_LEAD.getCode().equals(loginOerpators.getRoleType())){
					if("48502000".equals(loginOerpators.getOneagentid())){
						operators.setFlag(Constance.OPERATORS_FLAG_SELF);
						operators.setOneagentid("48502000");
					}else{
						operators.setOneagentid(loginOerpators.getOneagentid());
						operators.setFlag(Constance.OPERATORS_FLAG_SELF);
					}
				}else{
					operators.setOneagentid(loginOerpators.getOneagentid());
					operators.setFlag(Constance.OPERATORS_FLAG_SELF);
				}
				if(Role.RISK_CONTROL_LEAD.getCode().equals(operators.getRoleType()) || Role.RISK_CONTROL_OPERATORS.getCode().equals(operators.getRoleType())){
                                    operators.setAgentType("1");
                                }else{
                                    operators.setAgentType("0");
                                }
				List<OperRole> operRoleList = new ArrayList<OperRole>();
				if(Role.MARKET_DIRECT.getCode().equals(operators.getRoleType())||Role.MARKET_LEAD.getCode().equals(operators.getRoleType())){
					if("-1".equals(areaId)&&!loginOerpators.getRoleType().equals(Role.AGENT.getCode())){
						operators.setAreaIdRole("-1");
					}else{
						if(StringUtils.isEmpty(agentTo)){
							addActionMessage("请选择管理代理商");
							return INPUT;
						}
						String[] agentStr = agentTo.split(",");
						for(int i=0;i<agentStr.length;i++){
							OperRole operRole = new OperRole();
							operRole.setAgentId(agentStr[i]);
							operRole.setAreaCode(areaId);
							operRole.setInsCode(operators.getOrgCode());
							operRoleList.add(operRole);
						}
						operators.setOperRoleList(operRoleList);
					}
				}
				if(roleTypes.equals(Role.O_MANAGER.getCode())){
					Operators operatorsR = merchantServices.queryOperByRoleAndOrg(loginOerpators.getRoleType(), loginOerpators.getOrgCode());
					if(operatorsR!=null){
						addActionMessage("机构号"+loginOerpators.getOrgCode()+"的机构管理员已经存在");
						return INPUT;
					}
				}
				
				pwd = merchantServices.addMerchant(operators,loginOerpators);
		
	    }catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}

		logger.info("【"+loginOerpators.getAccountNo()+"】添加账号【"+operators.getAccountNo()+"】成功");
		getRequest().setAttribute("msg", "【"+loginOerpators.getAccountNo()+"】添加账号【"+operators.getAccountNo()+"】成功,初始密码" + pwd);
		return SUCCESS;
	}
	
	@Action(value = "init", results = {
			@Result(name = "success", location = "/pages/regist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	
	@SuppressWarnings("unused")
	//@Validations(requiredStrings = { @RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "user.userAccount", message = "请输入[登陆用户]") })
	public String init()throws Exception  {
		initSomeDataForAction();
		
		try {
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

			if(!logingOperators.getRoleType().equals(Role.SYSTEM.getCode())&&!logingOperators.getRoleType().equals(Role.O_MANAGER.getCode())&&!logingOperators.getRoleType().equals(Role.AGENT.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			if(logingOperators.getRoleType().equals(Role.SYSTEM.getCode())){
				orgList=orgService.queryAllOrgList();
			}else{
				TblInsInf tblInsInf = new TblInsInf();
				tblInsInf = orgService.queryOrgByOrgCode(logingOperators.getOrgCode());
				orgList.add(tblInsInf);
			}
			areaList=orgService.listAreaByOrgCode(logingOperators.getOrgCode());
			roleTypes=dealRoleType(logingOperators, ConfigProperties.getRoleTypeProperties());
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("加载代理商基本信息出错！！");
		}
		return SUCCESS;
	}
	
	@Action(value="queryRoleByOrgCode")
	public void queryRoleByOrgCode(){
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			roleTypes = dealRoleTypeByOrgCode(logingOperators.getRoleType(),logingOperators.getOrgCode(),orgCode, ConfigProperties.getRoleTypeProperties());
			json.put("roleTypes", roleTypes);
			pw.write(json.toString());
						
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			if(pw != null){
				pw.close();
			}
		}
	}
	
	@Action(value="queryAgentBySupAgent")
	public void queryAgentBySupAgent(){
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			List<TblOrgMain> list = agentService.queryOrgMainListByArea(areaId);
			json.put("operatorList", list);
			pw.write(json.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			if(pw != null){
				pw.close();
			}
		}
	}
	
	 
	
	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getInitPageSize()
	 */
	/*
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
*/
	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (MerchantSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_MERCHANT);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_MERCHANT, searchCondition);
	}
	/**
	 * @return the searchCondition
	 */
	public MerchantSearchCondition getSearchCondition() {
		
		return searchCondition;
	}
	/**
	 * @param searchCondition the searchCondition to set
	 */
	public void setSearchCondition(MerchantSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}
	/**
	 * @param msg the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @return the profitRsList
	 */
	public List<Object> getProfitRsList() {
		return profitRsList;
	}
	/**
	 * @param profitRsList the profitRsList to set
	 */
	public void setProfitRsList(List<Object> profitRsList) {
		this.profitRsList = profitRsList;
	}
	/**
	 * @return the profitModelHead
	 */

	public Operators getOperators() {
		return operators;
	}
	public void setOperators(Operators operators) {
		this.operators = operators;
	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}
	public List<TblArea> getAreaList() {
		return areaList;
	}
	public void setAreaList(List<TblArea> areaList) {
		this.areaList = areaList;
	}
	
}
